package calculator;

import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JPanel;
import javax.swing.JTextField;

public class KeyPad extends JPanel {
	
	private JPanel buttonPanel;
	private JButton clearButton;
	private JTextField display;
	
	public KeyPad()
	{
		
		setLayout(new BorderLayout());
		
		//A display
		display = new JTextField();
		add(display, "North");
		
		
		//The buttons
		
		buttonPanel = new JPanel();
		buttonPanel.setLayout(new GridLayout(4,3));
		
		addButton("7");
		addButton("8");
		addButton("9");
		addButton("4");
		addButton("5");
		addButton("6");
		addButton("1");
		addButton("2");
		addButton("3");
		addButton("0");
		
		//A "clear" button
		
		clearButton = new JButton("CE");
		buttonPanel.add(clearButton);
		
		class ClearButtonListener implements ActionListener
		{
			public void actionPerformed(ActionEvent event)
			{
				display.setText("");
			}
		}
		
		ActionListener listener = new ClearButtonListener();
		
		clearButton.addActionListener(listener);
		
		add(buttonPanel, "Center");				
		
		
	}
	
	private void addButton(final String label)
	{
		class DigitButtonListener implements ActionListener
		{
			public void actionPerformed(ActionEvent event)
			{
				display.setText(display.getText() + label);
			}
		}
		
		JButton button = new JButton(label);
		buttonPanel.add(button);
		ActionListener listener = new DigitButtonListener();
		button.addActionListener(listener);
		
	}

}
